<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts';
require('echarts/theme/macarons'); // echarts theme
import resize from './mixins/resize';

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '500px'
    },
    seriesData: {
      type: Array,
      required: true
    },
    legendData: {
      type: Array,
      required: true
    },
    title: {
      type: String,
      default: ''
    },
    seriesName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null,
      chartData: {
        title: {
          text: this.title, // 标题
          subtext: '',
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'horizontal',
          left: 'left',
          top: '40',
          data: this.legendData
        },
        series: [
          {
            name: this.seriesName, // 悬浮窗主标题
            type: 'pie',
            radius: '60%',
            center: ['50%', '60%'],
            data: this.seriesData, // 数据对象数组
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons');
      this.chart.setOption(this.chartData);
    }
  }
};
</script>
